package com.ruoyi.common.qy.utils;

import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AsyncVideoDownloader {

    private static final ExecutorService downloadExecutor =
        Executors.newFixedThreadPool(3);

    /**
     * 异步下载视频
     * @param videoUrl 视频URL
     * @param outputPath 输出路径
     * @return CompletableFuture用于异步处理
     */
    public static CompletableFuture<Void> downloadVideoAsync(String videoUrl, String outputPath) {
        return CompletableFuture.runAsync(() -> {
            try {
                System.out.println("开始异步下载: " + videoUrl);
                VideoDownloaderJava8.downloadVideo(videoUrl, outputPath);
                System.out.println("异步下载完成: " + outputPath);
            } catch (IOException e) {
                throw new RuntimeException("下载失败: " + videoUrl, e);
            }
        }, downloadExecutor);
    }

    /**
     * 关闭线程池
     */
    public static void shutdown() {
        downloadExecutor.shutdown();
    }

    public static void main(String[] args) {
        try {
            String[] videoUrls = {
                "https://example.com/video1.mp4",
                "https://example.com/video2.mp4",
                "https://example.com/video3.mp4"
            };

            // 创建多个异步下载任务
            CompletableFuture<?>[] futures = new CompletableFuture[videoUrls.length];

            for (int i = 0; i < videoUrls.length; i++) {
                String outputPath = "downloads/async_video" + (i + 1) + ".mp4";
                futures[i] = downloadVideoAsync(videoUrls[i], outputPath);
            }

            // 等待所有下载完成
            CompletableFuture.allOf(futures)
                .thenRun(() -> {
                    System.out.println("所有视频下载完成！");
                    shutdown();
                })
                .exceptionally(e -> {
                    System.err.println("下载过程中出现错误: " + e.getMessage());
                    shutdown();
                    return null;
                });

            // 主线程可以继续执行其他任务
            System.out.println("下载任务已提交，主线程继续执行...");

            // 等待异步任务完成（在实际应用中可能不需要）
            Thread.sleep(30000);

        } catch (Exception e) {
            e.printStackTrace();
            shutdown();
        }
    }
}
